package top.cdmrx.www.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.cdmrx.common.R;
import top.cdmrx.www.demo.service.MsmService;
import top.cdmrx.www.demo.utils.RandomUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Mr.陈 time on 2021/11/30 | 13:13
 **/
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmContoller {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //如果缓存中存在就不重复发送
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.success();
        }

        //生成随机数，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        boolean isSend = msmService.send(map, phone, "SMS_228846907");
        if (isSend){
            //发送成功就把验证码存到redis缓存中
            //并设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success();
        }else {

            return R.fail().message("短信发送失败！！！");
        }
    }
}
